package com.wangxiaonan.coupon.config;

import net.sf.ehcache.config.CacheConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Ehcache 缓存设置
 *
 * @Author: wangxiaonan
 * @Date: 2018/8/28
 **/
@Configuration
@EnableCaching
public class EhcacheConfig implements CachingConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(EhcacheConfig.class);

    @Bean
    public net.sf.ehcache.CacheManager ehCacheManager() {
        logger.info("---------------- start init ehcache ----------------");
        CacheConfiguration cacheConfiguration = new CacheConfiguration();
        cacheConfiguration.setName("coupon_infos");
        cacheConfiguration.setMemoryStoreEvictionPolicy("FIFO");
        cacheConfiguration.setMaxEntriesLocalHeap(100);
        cacheConfiguration.setTimeToIdleSeconds(7200);
        cacheConfiguration.setTimeToLiveSeconds(7200);
        net.sf.ehcache.config.Configuration config = new net.sf.ehcache.config.Configuration();
        config.addCache(cacheConfiguration);
        return net.sf.ehcache.CacheManager.newInstance(config);
    }

    @Bean
    @Override
    public CacheManager cacheManager() {
        return new EhCacheCacheManager(ehCacheManager());
    }

    @Bean
    @Override
    public CacheResolver cacheResolver() {
        return null;
    }

    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new SimpleKeyGenerator();
    }

    @Bean
    @Override
    public CacheErrorHandler errorHandler() {
        return null;
    }
}
